package com.thinkingcoder.tcconfig.client.config;

import java.util.Arrays;
import java.util.Optional;

import org.springframework.beans.factory.support.AbstractBeanDefinition;
import org.springframework.beans.factory.support.BeanDefinitionBuilder;
import org.springframework.beans.factory.support.BeanDefinitionRegistry;
import org.springframework.context.annotation.ImportBeanDefinitionRegistrar;
import org.springframework.core.type.AnnotationMetadata;

import com.thinkingcoder.tcconfig.client.value.SpringValueProcessor;

import lombok.extern.slf4j.Slf4j;

/**
 * register tc config bean.
 */
@Slf4j
public class TcConfigRegistrar implements ImportBeanDefinitionRegistrar {

    @Override
    public void registerBeanDefinitions(AnnotationMetadata importingClassMetadata, BeanDefinitionRegistry registry) {

        registerClass(registry, PropertySourcesProcessor.class);
        registerClass(registry, SpringValueProcessor.class);

    }

    private static void registerClass(BeanDefinitionRegistry registry, Class<?> clz) {
        log.info("Register {}", clz.getName());

        Optional<String> first =
            Arrays.stream(registry.getBeanDefinitionNames()).filter(temp -> clz.getName().equals(temp)).findFirst();
        if (first.isPresent()) {
            log.info("{} already registered", clz.getName());
            return;
        }

        AbstractBeanDefinition beanDefinition = BeanDefinitionBuilder.genericBeanDefinition(clz).getBeanDefinition();
        registry.registerBeanDefinition(clz.getName(), beanDefinition);
    }

}
